<?php
/**
 * 階段成績輸入
 * @author cik
 *
 */
class Score_Model_Stage extends Score_Model_Score
{
    /**
     * 全學期次別
     * @var integer
     */
    const WHOLE_STAGE_SCORE = 255;

    public function __construct($sn,$stage)
    {
        parent::__construct($sn);
        $this->setStage($stage);
    }

    /**
     *  學生階段成績
     * @param integer $stage
     * @return Array
     */
    public function getScores()
    {
        if (!$this->_sn)
        return false;

        if ($this->_isElective) {
            $q = Doctrine_Query::create()
            ->select('s.student_sn')
            ->from('Student_Model_StudentScoreElectiveStudent s')
            ->leftJoin('s.Student_Model_StudentScoreElectiveGroup g')
            ->where('g.teacher_course_sn=?',$this->_teacherCourse->sn );
            foreach($q->fetchArray() as $row)
            $studentArr[] = $row['student_sn'];
        }

        $q = Doctrine_Query::create()
        ->select('a.*, b.subject_sn as subject_sn, b.test_kind AS test_kind')
        ->from('Student_Model_StudentScoreStageDetail a')
        ->leftJoin('a.Student_Model_StudentScoreStage b')
        ->where('b.subject_sn=?',$this->_teacherCourse->subject_sn)
        ->andWhere('b.test_sort=?',$this->_currStage);
        if ($this->_isElective)
        $q->whereIn('a.student_sn',$studentArr);
        else
        $q->andWhere('b.class_sn=?', $this->_teacherCourse->class_sn);
//        echo $this->_teacherCourse->subject_sn.'--'. $this->_currStage,'--'.$this->_teacherCourse->class_sn;
//echo $q->getSqlQuery();
        $res = $q->fetchArray();

        $tempArr = array();

        foreach ($res  as $row) {
            $tempArr[$row['student_sn']][$row['test_kind']] = $row['score'];
        }
        return $tempArr;
    }

    /**
     * 儲存成績
     * @param $stage  階段
     * @param $scores 成績陣列
     * @return unknown_type
     */
    public function save($stage , $scores)
    {
        $teacherSn = Teacher_Model_Teacher::getSnById();
        foreach ($scores as $test_kind=>$val) {
            // 一般課程,先找出 master sn ,如沒有則新增
            if (! $this->isElective()) {
                $q = Doctrine_Query::create()
                ->select('sn')
                ->from('Student_Model_StudentScoreStage')
                ->where('subject_sn=?', $this->getTeacherCourse()->subject_sn)
                ->andWhere('class_sn=?', $this->getTeacherCourse()->class_sn)
                ->andWhere('test_kind=?', $test_kind)
                ->andWhere('test_sort=?', $stage);
                // 找出 master 的 s
                if (!$stageSn = $q->fetchOne()->sn) {
                    $studentScoreStage = new Student_Model_StudentScoreStage();
                    $studentScoreStage->subject_sn = $this->getTeacherCourse()->subject_sn;
                    $studentScoreStage->class_sn = $this->getTeacherCourse()->class_sn;
                    $studentScoreStage->test_kind = $test_kind;
                    $studentScoreStage->test_sort = $stage;
                    $studentScoreStage->teacher_sn = $teacherSn;
                    $studentScoreStage->save();
                    $stageSn = $studentScoreStage->sn;
                }
            }
            // 填入成績
            foreach ($val as $studentSn => $score) {
                if ($this->isElective()) {
                    $tempArr = explode("-",$studentSn);
                    $studentSn = (int)$tempArr[1];
                    // 分組班學生來自各班,須逐一學生查詢 student_score_stage 的 sn
                    // 如是未建立,則新增,並將任課教師應
                    $q = Doctrine_Query::create()
                    ->select('sn')
                    ->from('Student_Model_StudentScoreStage')
                    ->where('subject_sn=?', $this->getTeacherCourse()->subject_sn)
                    ->andWhere('class_sn=?', $tempArr[0])
                    ->andWhere('test_kind=?', $test_kind)
                    ->andWhere('test_sort=?', $stage);
                    // 找出 master 的 sn
                    if (!$stageSn = $q->fetchOne()->sn) {
                        $studentScoreStage = new Student_Model_StudentScoreStage();
                        $studentScoreStage->subject_sn = $this->getTeacherCourse()->subject_sn;
                        $studentScoreStage->class_sn = $tempArr[0];
                        $studentScoreStage->test_kind = $test_kind;
                        $studentScoreStage->test_sort = $stage;
                        // $studentScoreStage->teacher_sn = $teacherSn;
                        $studentScoreStage->save();
                        $stageSn = $studentScoreStage->sn;
                    }
                }
                if ($score !== '') {
                    $studentScoreStageDetail = new Student_Model_StudentScoreStageDetail();
                    $res = $studentScoreStageDetail->getTable()
                    ->findBySql("stage_sn=? AND student_sn=?",array($stageSn,$studentSn))
                    ->getFirst();
                    if ($res)
                    $studentScoreStageDetail->assignIdentifier($res->sn);

                    $studentScoreStageDetail->stage_sn = $stageSn;
                    $studentScoreStageDetail->student_sn = (int) $studentSn;
                    $studentScoreStageDetail->score = (float) $score;
                    $studentScoreStageDetail->teacher_sn = $teacherSn;
                    $studentScoreStageDetail->save();
                }
            }

        }
    }

    /**
     * 設定目前階段
     * @param $stage
     */
    public function setStage($stage)
    {
        //   如果是全學期打一次成績
        if ($this->_subjectSet->scored_mode == 0 ) {
            $stage = self::WHOLE_STAGE_SCORE;
        }
        else {
            if ($stage == self::WHOLE_STAGE_SCORE)
            $stage = 0;
            if (!$stage ) {
                //  查詢目前應輸入的階段
                $q = Doctrine_Query::create()
                ->select('MAX(test_sort) AS mm')
                ->leftJoin('Student_Model_StudentScoreStage ')
                ->where('subject_sn=?', $this->_teacherCourse->subject_sn)
                ->andWhere('class_sn=?',$this->_teacherCourse->class_sn)
                ->andWhere('sendmit=?', 'Y');
                $res = $q->fetchOne();

                $stage = $res->mm;
                if ($stage) {
                    $stage_sn = $res->sn;
                    // 如果已傳送 次數小於總考次時,自動切換到下一階段
                    if ($stage < $this->_examine->period)
                    $stage++;
                }
                else
                $stage =  1;
            }
        }
        $this->_currStage = $stage;


    }


    /**
     *  階段成績平均
     * @return unknown_type
     */
    public function getScoreAverge()
    {

        if ($this->_isElective) {
            $q = Doctrine_Query::create()
            ->select('s.student_sn')
            ->from('Student_Model_StudentScoreElectiveStudent s')
            ->leftJoin('s.Student_Model_StudentScoreElectiveGroup g')
            ->where('g.teacher_course_sn=?',$this->_teacherCourse->sn );
            foreach($q->fetchArray() as $row)
            $studentArr[] = $row['student_sn'];
        }

        $q = Doctrine_Query::create()
        ->select('a.student_sn , a.score, b.test_kind AS test_kind')
        ->from ('Student_Model_StudentScoreStageDetail a')
        ->leftJoin('a.Student_Model_StudentScoreStage b')
        ->where('b.subject_sn=?',$this->_teacherCourse->subject_sn)
        ->andWhere('b.test_sort=?',$this->_currStage);
        if ($this->_isElective)
        $q->andWhereIn('a.student_sn',$studentArr);
        else
        $q->andWhere('b.class_sn=?', $this->_teacherCourse->class_sn);

        $q->groupBy('a.student_sn, b.test_kind');

        $res = $q->fetchArray();
        $radioArr = $this->_examine->ratio[$this->_currStage];
        $totalRatio = $radioArr[1] + $radioArr[2];
        $arr = array();
        foreach($res as $row) {
            $arr[$row['student_sn']] += $radioArr[$row['test_kind']] * $row['score'] / $totalRatio ;
        }

        return $arr;
    }


}